export type VerificationResultItem = {
  edgeId?: string;
  nodeId?: string;
  errorMsgList: string[];
  success: boolean;
};

const isExecutingAtom = atom<boolean>({
  key: 'isExecutingResults',
  default: false
});

const resultsListAtom = atom<VerificationResultItem[]>({
  key: 'verificationResults',
  default: []
});

export const useNodeVerificationResults = () => {
  const [isExecuting, setIsExecuting] = useRecoilState(isExecutingAtom);
  const [verificationResultList, setVerificationResultList] = useRecoilState(resultsListAtom);

  const addResults = (results: VerificationResultItem) => {
    setVerificationResultList((prev) => {
      const index = prev.indexOf(results);
      if (index > -1) {
        prev.splice(index, 1, results);
        return [...prev];
      }
      return [...prev, results];
    });
  };

  const clearResults = () => {
    setVerificationResultList([]);
    setIsExecuting(false);
  };

  const hasExecResult = verificationResultList.length > 0;

  return {
    isExecuting,
    hasExecResult,
    setIsExecuting,
    verificationResultList,
    setVerificationResultList,
    addResults,
    clearResults
  };
};
